package com.vdong.interactive.course.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdong.interactive.course.common.enums.PeddleGoodsApplyStatusEnum;
import com.vdong.interactive.course.common.enums.PeddleGoodsOpenEnum;
import com.vdong.interactive.course.common.enums.ProcessExceptionEnum;
import com.vdong.interactive.course.common.exception.ProcessException;
import com.vdong.interactive.course.entity.dto.*;
import com.vdong.interactive.course.entity.dto.base.BasePeddleGoodsDTO;
import com.vdong.interactive.course.entity.mo.Goods;
import com.vdong.interactive.course.entity.mo.GoodsPeddle;
import com.vdong.interactive.course.repository.dao.GoodsMapper;
import com.vdong.interactive.course.repository.dao.GoodsPeddleMapper;
import com.vdong.interactive.course.service.PeddleGoodsService;
import com.vdong.kpay.basics.dubbo.api.backend.StoreService;
import com.vdong.kpay.basics.dubbo.api.frontend.AppCourseService;
import com.vdong.kpay.basics.dubbo.api.frontend.AppLecturerService;
import com.vdong.kpay.basics.dubbo.pojo.backend.StoreInfo;
import com.vdong.kpay.basics.dubbo.pojo.backend.UserInfo;
import com.vdong.kpay.basics.dubbo.pojo.frontend.AppCourseSub;
import com.vdong.kpay.basics.dubbo.pojo.frontend.AppUserLecturer;
import com.vdong.member.account.facade.AccountSystemUserFacadeService;
import com.vdong.trade.order.facade.OrderFacade;
import lombok.extern.log4j.Log4j2;
import org.lamb.framework.common.remote.FacadeResult;
import org.lamb.framework.common.util.FacadeResultUtils;
import org.lamb.framework.common.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@org.springframework.stereotype.Service
/**
 * 分销商品
 */
@Log4j2
public class PeddleGoodsServiceImpl implements PeddleGoodsService {

    private static final String PREFIX = "http://";

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsPeddleMapper goodsPeddleMapper;

    @Reference
    private AppCourseService appCourseService;

    @Reference
    private AppLecturerService appLecturerService;

    @Reference
    private AccountSystemUserFacadeService accountSystemUserFacadeService;

    @Reference
    private OrderFacade orderFacadeService;

    @Reference(version = "1.0.0")
    private StoreService storeService;

    @Value("${peddle.goods.url}")
    private String peddleGoodsUrl;

    @Override
    public PageInfo<GoodsPeddleListDTO> getPeddleGoodsList(Integer checkState, Integer openState, Integer classifyType, String keyword, Long sysUserId, Integer isShow, Integer sort, Integer page, Integer pageSize) {
        PageInfo<GoodsPeddleListDTO> result = PageHelper.startPage(page, pageSize, true).doSelectPageInfo(() ->
                goodsPeddleMapper.findGoodsPeddleList(checkState, classifyType, keyword, sysUserId, null, null, openState, sort, isShow,null));

        result.getList().forEach(goodsPeddleListDTO->{
            Map<String,Object> map = new HashMap<>();
            map.put("productId",goodsPeddleListDTO.getPeddleGoodsId());
            String salesJsonStr = orderFacadeService.getSalesAndEarningsByGoods(JSON.toJSONString(map));
            FacadeResult<OrderFacadeSalesDTO> facadeSalesDTOFacadeResult = FacadeResultUtils.stringToFacadeBean(salesJsonStr,OrderFacadeSalesDTO.class);
            if (facadeSalesDTOFacadeResult.isSuccess()){
                goodsPeddleListDTO.setSalesNum(facadeSalesDTOFacadeResult.getData().getTotalSales());
            }
        });
        return result;
    }

    public PageInfo<GoodsPeddleListDTO> getStorePeddleGoodsList(Integer checkState, Integer openState, Integer classifyType, String keyword, Long sysUserId, Integer isShow, Integer sort, Integer page, Integer pageSize) {
        PageInfo<GoodsPeddleListDTO> result = PageHelper.startPage(page, pageSize, true).doSelectPageInfo(() ->
                goodsPeddleMapper.findGoodsPeddleList(checkState, classifyType, keyword, sysUserId, null, null, openState, sort, isShow,null));

        result.getList().forEach(goodsPeddleListDTO->{
            Map<String,Object> map = new HashMap<>();
            map.put("productId",goodsPeddleListDTO.getPeddleGoodsId());
            String salesJsonStr = orderFacadeService.getSalesAndEarningsByGoods(JSON.toJSONString(map));
            FacadeResult<OrderFacadeSalesDTO> facadeSalesDTOFacadeResult = FacadeResultUtils.stringToFacadeBean(salesJsonStr,OrderFacadeSalesDTO.class);
            if (facadeSalesDTOFacadeResult.isSuccess()){
                goodsPeddleListDTO.setSalesNum(facadeSalesDTOFacadeResult.getData().getTotalSales());
            }
        });
        return result;
    }

    @Override
    public PageInfo<GoodsPeddleListDTO> getIndexGoodsChoice(String keyword, Integer sort, Integer page, Integer pageSize) {
        PageInfo<GoodsPeddleListDTO> result = PageHelper.startPage(page, pageSize, true).doSelectPageInfo(() ->
                goodsPeddleMapper.findGoodsPeddleList(PeddleGoodsApplyStatusEnum.CHECK_PASS.getCode(), null, keyword, null, null, null, PeddleGoodsOpenEnum.PUTAWAY.getCode(), sort, 0,null));
        return result;
    }

    @Override
    public PageInfo<GoodsPeddleListDTO> rotationGoodsChoice(String keyword, Integer sort, Integer page, Integer pageSize) {
        PageInfo<GoodsPeddleListDTO> result = PageHelper.startPage(page, pageSize, true).doSelectPageInfo(() ->
                goodsPeddleMapper.findGoodsPeddleList(PeddleGoodsApplyStatusEnum.CHECK_PASS.getCode(), null, keyword, null, null, null, PeddleGoodsOpenEnum.PUTAWAY.getCode(), sort, null,null));
        return result;
    }

    @Override
    public BasePeddleGoodsDTO getBasePeddleGoodsDetail(Long peddleGoodsId) {
        GoodsPeddle goodsPeddle = goodsPeddleMapper.selectByPrimaryKey(peddleGoodsId);
        if (Objects.isNull(goodsPeddle)) {
            throw new ProcessException(ProcessExceptionEnum.EB00000003);
        }
        Goods goods = goodsMapper.selectByPrimaryKey(goodsPeddle.getGoodsId());
        if (Objects.isNull(goods)) {
            throw new ProcessException(ProcessExceptionEnum.EB00000003);
        }
        BasePeddleGoodsDTO peddleGoodsDetail = new BasePeddleGoodsDTO();
        BeanUtils.copyProperties(goods, peddleGoodsDetail);
        BeanUtils.copyProperties(goodsPeddle, peddleGoodsDetail);
        peddleGoodsDetail.setSysUserId(goodsPeddle.getCreateUser().toString());
        peddleGoodsDetail.setPeddleGoodsId(goodsPeddle.getId());
        return peddleGoodsDetail;
    }

    @Override
    public PeddleGoodsDetailDTO getPeddleGoodsDetail(Long peddleGoodsId) {
        BasePeddleGoodsDTO basePeddleGoodsDTO = this.getBasePeddleGoodsDetail(peddleGoodsId);
        PeddleGoodsDetailDTO peddleGoodsDetailDTO = new PeddleGoodsDetailDTO();
        BeanUtils.copyProperties(basePeddleGoodsDTO, peddleGoodsDetailDTO);
        // TODO 设置详情具体字段
        StoreInfo storeInfo = storeService.getStoreBaseInfo(basePeddleGoodsDTO.getPlatformStoreId());
        peddleGoodsDetailDTO.setStoreName(storeInfo.getName());
        peddleGoodsDetailDTO.setStoreLogUrl(PREFIX + storeInfo.getBucketDomain() + "/" + storeInfo.getLogoUrl());

        Map<String,Object> map = new HashMap<>();
        map.put("productId",basePeddleGoodsDTO.getPeddleGoodsId());
        String salesJsonStr = orderFacadeService.getSalesAndEarningsByGoods(JSON.toJSONString(map));
        FacadeResult<OrderFacadeSalesDTO> facadeSalesDTOFacadeResult = FacadeResultUtils.stringToFacadeBean(salesJsonStr,OrderFacadeSalesDTO.class);
        if (facadeSalesDTOFacadeResult.isSuccess()){
            peddleGoodsDetailDTO.setTotalProfit(facadeSalesDTOFacadeResult.getData().getTotalProfit());
            peddleGoodsDetailDTO.setTotalSalesNum(new BigDecimal(facadeSalesDTOFacadeResult.getData().getTotalSales()));
        }

        return peddleGoodsDetailDTO;
    }

    @Override
    public PageInfo<CourseSubCatalogDTO> pageCourseSub(Long peddleGoodsId, Integer page, Integer pageSize) {
        GoodsPeddle goodsPeddle = goodsPeddleMapper.selectByPrimaryKey(peddleGoodsId);
        PageInfo<AppCourseSub> result = appCourseService.listSubDubboPage(goodsPeddle.getPlatformGoodsId(), true, page, pageSize);

        List<CourseSubCatalogDTO> subCatalogDTOS = new ArrayList<>();
        result.getList().forEach(e -> {
            CourseSubCatalogDTO subCatalogDTO = new CourseSubCatalogDTO();
            subCatalogDTO.setSubId(e.getId());
            subCatalogDTO.setSubLength(e.getSubLength());
            subCatalogDTO.setIsCharge(e.getSubLength());
            subCatalogDTO.setSubName(e.getSubName());
            subCatalogDTO.setSubNo(e.getSubNo());
            subCatalogDTO.setSubType(e.getSubType().intValue());
            subCatalogDTO.setSubUrl(e.getSubUrl());
            subCatalogDTOS.add(subCatalogDTO);
        });
        PageInfo pageInfo = new PageInfo(subCatalogDTOS);
        BeanUtils.copyProperties(result, pageInfo, "list");
        return pageInfo;
    }

    @Override
    public CourseSubCatalogDTO getCourseSubDetail(Long subId) {
        CourseSubCatalogDTO subCatalogDTO = new CourseSubCatalogDTO();
        AppCourseSub courseSub = appCourseService.getSubDetailDubbo(subId);
        subCatalogDTO.setSubId(courseSub.getId());
        subCatalogDTO.setSubLength(courseSub.getSubLength());
        subCatalogDTO.setIsCharge(courseSub.getSubLength());
        subCatalogDTO.setSubName(courseSub.getSubName());
        subCatalogDTO.setSubNo(courseSub.getSubNo());
        subCatalogDTO.setSubType(courseSub.getSubType().intValue());
        subCatalogDTO.setSubUrl(courseSub.getSubUrl());
        return subCatalogDTO;
    }

    @Override
    public String getSubContext(Long subId) {
        return appCourseService.getSubContextDubbo(subId);
    }

    @Override
    public PageInfo<AppPeddleGoodsDTO> getAppPeddleGoodsPage(String keyword, Long categoryId, Long typeId, Integer classifyType, Integer sort, Integer isShow, Integer page, Integer pageSize) {
        PageInfo<GoodsPeddleListDTO> result = PageHelper.startPage(page, pageSize, true).doSelectPageInfo(() ->
                goodsPeddleMapper.findGoodsPeddleList(1, classifyType, keyword, null, categoryId, typeId, PeddleGoodsOpenEnum.PUTAWAY.getCode(), sort, isShow,null));

        Page pageBean = (Page) result.getList();
        List<AppPeddleGoodsDTO> peddleGoodsList = new ArrayList<>();
        result.getList().forEach(e -> {
            BigDecimal price = new BigDecimal(e.getPrice());
            BigDecimal peddleRate = new BigDecimal(e.getPeddleRate()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//            BigDecimal peddleRate = new BigDecimal(e.getPeddleRate());
            BigDecimal earnAmount = peddleRate.multiply(price).setScale(2, RoundingMode.HALF_UP);
            AppPeddleGoodsDTO appPeddleGoodsDTO = new AppPeddleGoodsDTO();
            appPeddleGoodsDTO.setPeddleGoodsId(e.getPeddleGoodsId());
            appPeddleGoodsDTO.setImageUrl(e.getImageUrl());
            appPeddleGoodsDTO.setPrice(e.getPrice());
            appPeddleGoodsDTO.setSubType(e.getSubType());
            appPeddleGoodsDTO.setArticleLink(e.getArticleLink());
            appPeddleGoodsDTO.setClassifyType(e.getClassifyType());
            appPeddleGoodsDTO.setCommission(e.getPeddleRate());
            appPeddleGoodsDTO.setCourseId(e.getPlatformGoodsId());
            appPeddleGoodsDTO.setCourseName(e.getGoodsName());
            appPeddleGoodsDTO.setEarnAmount(earnAmount.toString());//赚多少
            peddleGoodsList.add(appPeddleGoodsDTO);
        });

        pageBean.clear();
        pageBean.addAll(peddleGoodsList);
        return pageBean.toPageInfo();
    }

    @Override
    public AppPeddleGoodsDetailDTO getAppPeddleGoodsDetail(Long peddleGoodsId) {
        BasePeddleGoodsDTO basePeddleGoodsDTO = this.getBasePeddleGoodsDetail(peddleGoodsId);

        if (basePeddleGoodsDTO.getDeleted()){
            throw new ProcessException(ProcessExceptionEnum.EB00000003);
        }
        AppPeddleGoodsDetailDTO goodsDetail = new AppPeddleGoodsDetailDTO();
        goodsDetail.setGoodsIntroduction(basePeddleGoodsDTO.getGoodsIntroduction());
        goodsDetail.setGoodsName(basePeddleGoodsDTO.getGoodsName());
        goodsDetail.setImageUrl(basePeddleGoodsDTO.getImageUrl());
        goodsDetail.setLecturerId(basePeddleGoodsDTO.getAuthorId().toString());
        Map<String, Object> params = new HashMap<>();
        params.put("sysUserId", basePeddleGoodsDTO.getSysUserId());
        params.put("userType", 2);
        log.info("***********************************调用account服务******************************************" + JSON.toJSONString(params));
        String result = accountSystemUserFacadeService.getAccountSystemPeddleUserInfoBySysUserId(JSON.toJSONString(params));
        FacadeResult<AccountSystemUserInfoDTO> facadeResult = FacadeResultUtils.stringToFacadeBean(result, AccountSystemUserInfoDTO.class);
        log.info("***********************************调用account服务返回******************************************" + result);
        if (facadeResult.isSuccess()) {
            AccountSystemUserInfoDTO systemUserInfoDTO = facadeResult.getData();
            log.info("***********************************调用bascia服务服务返回******************************************" + result);
            if (!StringUtil.hasBlank(systemUserInfoDTO)) {
                String appId = storeService.getStoreWechatAppIdDubbo(Long.valueOf(systemUserInfoDTO.getPlatformInsideId()));
                goodsDetail.setPeddleGoodsUrl(PREFIX + appId + peddleGoodsUrl);
                log.info("获取到的penddleGoodsUrl为:" + goodsDetail.getPeddleGoodsUrl());
            }
        }

        UserInfo lecturer = appLecturerService.getLecturer(basePeddleGoodsDTO.getAuthorId());
        goodsDetail.setLecturerName(basePeddleGoodsDTO.getAuthorName());
        goodsDetail.setLecturerIntroduction(lecturer.getIntroduce());
        goodsDetail.setLecturerPic(lecturer.getPhotoUrl());
        goodsDetail.setPeddleGoodsId(basePeddleGoodsDTO.getPeddleGoodsId());
        goodsDetail.setPlatformGoodsId(basePeddleGoodsDTO.getPlatformGoodsId());
        goodsDetail.setPrice(basePeddleGoodsDTO.getPrice());

        Map<String,Object> map = new HashMap<>();
        map.put("productId",basePeddleGoodsDTO.getPeddleGoodsId());
        String salesJsonStr = orderFacadeService.getSalesAndEarningsByGoods(JSON.toJSONString(map));
        FacadeResult<OrderFacadeSalesDTO> facadeSalesDTOFacadeResult = FacadeResultUtils.stringToFacadeBean(salesJsonStr,OrderFacadeSalesDTO.class);
        if (facadeSalesDTOFacadeResult.isSuccess()){
            goodsDetail.setTodaySales(facadeSalesDTOFacadeResult.getData().getTodaySales());
            goodsDetail.setTotalSales(facadeSalesDTOFacadeResult.getData().getTotalSales());
        }

        BigDecimal peddleRate = new BigDecimal(basePeddleGoodsDTO.getPromoterProfitRatio()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal earnAmount = peddleRate.multiply(basePeddleGoodsDTO.getPrice()).setScale(2, RoundingMode.HALF_UP);

        goodsDetail.setEarnAmount(earnAmount.toString());//赚多少
        List<AppCourseSub> courseSubList = appCourseService.listSubDubbo(basePeddleGoodsDTO.getPlatformGoodsId(), false);
        List<CourseSubCatalogDTO> courseSubCatalogDTOS = new ArrayList<>();
        courseSubList.forEach(e -> {
            CourseSubCatalogDTO subCatalogDTO = new CourseSubCatalogDTO();
            subCatalogDTO.setSubId(e.getId());
            log.info("***********************************227******************************************");
            subCatalogDTO.setSubLength(e.getSubLength());
            subCatalogDTO.setIsCharge(e.getSubLength());
            subCatalogDTO.setSubName(e.getSubName());
            subCatalogDTO.setSubNo(e.getSubNo());
            subCatalogDTO.setSubType(e.getSubType().intValue());
            courseSubCatalogDTOS.add(subCatalogDTO);
        });
        goodsDetail.setCourseSubCatalog(courseSubCatalogDTOS);
        // TODO 设置详情具体字段
        return goodsDetail;
    }
}
